#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'heibbai@gmail.com'

import gdata.alt.appengine
import gdata.service
import gdata.photos.service
from google.appengine.ext import db

class AuthSubStoredToken(db.Model):
    user_email = db.StringProperty(required=True)
    session_token = db.StringProperty(required=True)

class TokenError(Exception): 
    pass

def UpgradeAndStoreToken(email,token):
    client = gdata.service.GDataService()
    gdata.alt.appengine.run_on_appengine(client)
    try:
        session_token = client.upgrade_to_session_token(token)
    except:
        raise TokenError
    else:
        stored_token = AuthSubStoredToken.gql('WHERE user_email = :1',email).get()
        token_str = str(session_token).split('=')[1]
        if stored_token:
            stored_token.session_token = token_str
            stored_token.put()
        else:
            new_token = AuthSubStoredToken(user_email = email,
                    session_token = token_str)
            new_token.put()
    return session_token

def LookupToken(email):
    stored_token = AuthSubStoredToken.gql('WHERE user_email = :1',email).get()
    if stored_token:
        return stored_token.session_token
    else:
        return None

def DeleteInvalidToken(email):
    stored_token = AuthSubStoredToken.gql('WHERE user_email = :1',email).get()
    if stored_token:
        return stored_token.delete()

def RevokeToken(email):
    '''
    Session tokens are long lived and not expired.
    RevokeToken () first try to revoken token from google data service,
    then delete it from datastore.
    '''
    stored_token = AuthSubStoredToken.gql('WHERE user_email = :1',email).get()
    if stored_token:
        try: 
            gd_client = gdata.photos.service.PhotosService()
            gd_client.SetAuthSubToken(stored_token)
            gdata.alt.appengine.run_on_appengine(gd_client)
            gd_client.RevokeAuthSubToken()
        except gdata.service.NonAuthSubToken:
            pass
        finally:
            stored_token.delete()
    return True

def IsAuthed(email):
    stored_token = AuthSubStoredToken.gql('WHERE user_email = :1',email).get()
    if stored_token:
        return True
    else:
        return False
